﻿using System.IO;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StyleAnalyzer;

namespace StyleAnalyzerTest
{
	[TestClass]
	public class ParserTest
	{
		StyleSheet css;

		[TestInitialize]
		public void Setup()
		{
			css = new StyleSheet();
			AnalyzeStyleSheet();
		}

		[TestMethod]
		public void ParseSimpleCss()
		{
			css.Analyze("body {font: normal 12pt arial; }");
			Assert.AreEqual("body{font:normal 12pt arial}", css.MinifiedOutput);
		}

		[TestMethod]
		public void ParseNumberOfSelectors()
		{
			int count = NumberOfOccurrences(css.MinifiedOutput, "{", RegexOptions.None);
			Assert.AreEqual(count, css.Rules.Count);
		}

		[TestMethod]
		public void Parse2()
		{
			Assert.AreEqual(181, css.Rules.Count);
		}

		[TestMethod]
		public void CheckPropertyNames()
		{
			foreach (CssRule rule in css.Rules)
			{
				foreach (string property in rule.Properties.Keys)
				{
					Assert.IsFalse(property.Contains(":"), "Property is wrongly parsed", property);
				}
			}
		}

		[TestMethod]
		public void CheckPropertyValues()
		{
			foreach (CssRule rule in css.Rules)
				foreach (string property in rule.Properties.Keys)
				{
					Assert.IsFalse(string.IsNullOrEmpty(rule.Properties[property]));
				}
		}

		[TestMethod]
		public void IsSuccesfullyParsed()
		{
			bool success = css.IsSuccessfullyParsed;

			foreach (CssRule rule in css.Rules)
			{
				if (!rule.IsSuccessfullyParsed)
				{
					success = false;
				}
			}

			Assert.IsFalse(success);
		}

		private void AnalyzeStyleSheet()
		{
			using (StreamReader reader = new StreamReader(@"D:\style.css"))
			{
				css.Analyze(reader.ReadToEnd());
			}
		}

		public static int NumberOfOccurrences(string text, string stringToFind, RegexOptions options)
		{
			if (text == null || stringToFind == null)
			{
				return 0;
			}

			Regex reg = new Regex(stringToFind, options);

			return reg.Matches(text).Count;
		}
	}
}
